<template>
  <VPage>
    <el-row :gutter="10" class="mb-[6px]" v-loading="loading">
      <el-col :span="4">
        <el-select
          v-model="data.mode"
          placeholder="Select"
          style="width: 100%"
          disabled
        >
          <el-option
            v-for="item in modeDesign"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="20">
        <el-space>
          <el-radio-group v-model="data.paperSize">
            <el-radio-button
              :label="type"
              v-for="(value, type) in paperTypes"
              :key="value"
              @click="handlePageSize(value)"
            />
            <el-popover :visible="pageVisible" placement="bottom" :width="200">
              <p>设置纸张宽高(mm)</p>
              <div>
                <NumberRange v-model="range"></NumberRange>
              </div>
              <div style="text-align: right; margin: 5px">
                <el-button
                  size="small"
                  text
                  @click="
                    pageVisible = false;
                    range.min = 0;
                    range.max = 0;
                  "
                  >取消</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="
                    handlePageSize({ width: range.min, height: range.max });
                    pageVisible = false;
                    range.min = 0;
                    range.max = 0;
                  "
                  >确认</el-button
                >
              </div>
              <template #reference>
                <el-radio-button
                  label="自定义纸张"
                  @click="pageVisible = true"
                />
              </template>
            </el-popover>
          </el-radio-group>
          <el-space>
            <el-button
              @click="updateZoom(-0.1)"
              :disabled="data.pageZoom <= 0.5"
              >-</el-button
            >
            <el-input v-model="pageZoom" style="width: 70px" disabled>
            </el-input>
            <el-button @click="updateZoom(0.1)" :disabled="data.pageZoom >= 3"
              >+</el-button
            >
          </el-space>
        </el-space>
        <el-button @click="handlePreview">预览</el-button>
        <el-button @click="handleClodopPreview">c-lodop预览</el-button>
        <el-button @click="handlePrint">打印</el-button>
        <el-button @click="handleClodopPrint">c-lodop打印</el-button>
        <el-button @click="handleSave">保存</el-button>
        <el-button @click="handleClear">清空</el-button>
      </el-col>
    </el-row>
    <design ref="designRef" :mode="data.mode" @changePage="changePage" />
    <preview v-model="previewDialog" ref="previewRef" />
  </VPage>
</template>

<script setup>
import { ElMessage } from "element-plus";
import html2canvas from "html2canvas";
import design from "./design/index.vue";
import { paperTypes, modeDesign } from "./data.js";
import printData from "./print-data.js";
import NumberRange from "@/components/NumberRange/index.vue";
import preview from "./components/preview/index.vue";
import "@/assets/js/CLodopfuncs.js";
import { strHtml } from "./hooks/htmlContent";
import { LodopPrint } from "@/components/templateDesign/hooks/index.js";
import { base64ToFile } from "@/utils/tool.js";
import { upFileHttpRequest } from "@/hooks/upFile.js";
import { billUpdate } from "./api/index.js";
import useTagsViewStore from '@/store/modules/tagsView'
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const refresh = (obj) =>{
useTagsViewStore().delCachedView(obj).then(() => {
      const { path, query } = obj
      router.replace({
        path: path,
        query: query
      })
    })
}
refresh(route)
const data = reactive({
  paperSize: "A4",
  paperValue: {
    width: 210,
    height: 297,
  },
  scaleValue: 100,
  mode: "aProviderModule",
  pageZoom: 1,
});
const pageVisible = ref(false);
const designRef = ref();
const range = ref({ min: 0, max: 0 });
const pageZoom = ref("100%");
function findSizeByDimensions(width, height, sizes) {
  for (const key in sizes) {
    const size = sizes[key];
    if (size.width == width && size.height == height) {
      return key;
    }
  }
  return null;
}
//跳转过来的时候，根据参数设置纸张大小
// onMounted(() => {
//   nextTick(() => {

//   });
// });
const changePage = () => {
  const value = route.query;
  if (!value?.id) return;
  let matchingSize = findSizeByDimensions(
    Number(value?.bill_size_l || 21) * 10,
    Number(value?.bill_size_w || 29.7) * 10,
    paperTypes
  );
  if (matchingSize) {
    data.paperSize = matchingSize;
    data.paperValue = paperTypes[matchingSize];
    handlePageSize({
      width: paperTypes[matchingSize].width,
      height: paperTypes[matchingSize].height,
    });
  } else {
    data.paperSize = "自定义纸张";
    data.paperValue = {
      width: Number(value?.bill_size_l || 21) * 10,
      height: Number(value?.bill_size_w || 29.7) * 10,
    };
    handlePageSize({
      width: Number(value?.bill_size_l || 21) * 10,
      height: Number(value?.bill_size_w || 29.7) * 10,
    });
  }
};
const handlePageSize = (val) => {
  data.paperValue = val;
  designRef.value.setPageSize(val);
};
//将模板转化为oss并一起保存
const templatechangeFile = async () => {
  let hiprintTemplate = await designRef.value.getHiprintTemplate();
  let templateData = hiprintTemplate.getHtml(printData)[0].innerHTML;
  const virtualDiv = document.createElement("div");
  virtualDiv.innerHTML = templateData;
  document.body.appendChild(virtualDiv);
  const hiprintPrintPaperElement = virtualDiv.querySelector(
    ".hiprint-printPaper"
  );
  let data = {}
  // 使用 html2canvas 将 DOM 元素转为图片
 await html2canvas(hiprintPrintPaperElement, { scale: 2 }).then(async (canvas) => {
    const imageData = canvas.toDataURL("image/png");
    //获取时间戳
    let timestamp = new Date().getTime();
    let file = base64ToFile(imageData, `${timestamp}.png`);
    data = await upFileHttpRequest(file);
    document.body.removeChild(virtualDiv);
  });
  return data;
};
const handleSave = async () => {
  let img = await templatechangeFile();
  let hiprintTemplate = await designRef.value.getHiprintTemplate();
  let templateData = hiprintTemplate.getJson();
  console.log(templateData);
  let filed_config = []
  let printElements = templateData.panels[0].printElements
  let htmlData = {}
  console.log(printElements);
  for(let key in printElements){
    console.log(key);
    console.log(printElements[key]?.options?.field);
    let flage = false
    if(printElements[key]?.printElementType?.type=="table"){
      flage = true
    }
    if(printElements[key]?.options?.field){
      console.log(printElements[key]?.options?.field);
      filed_config.push(printElements[key]?.options?.field)
      if(flage){
        htmlData[printElements[key]?.options?.field] = []
      }else{
        htmlData[printElements[key]?.options?.field] = "${"+printElements[key]?.options?.field+"}"
      }
      console.log(htmlData);
    }
  }

  let html_temp = hiprintTemplate.getHtml(htmlData)[0].innerHTML;
  let html_str = strHtml(html_temp)
  try {
    loading.value = true;
    const { id, type, bill_size_l, bill_size_w } = route.query;
    let data = {
      id,
      bill_json: templateData,
      bill_img: img?.oss_path || "",
      bill_size_l,
      bill_size_w,
      bill_html_config:filed_config,
      bill_html:html_str
    };
    const { code, message } = await billUpdate(type, data);
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("保存成功");
  } catch (error) {}finally{
    loading.value = false;
  }
};

const updateZoom = (val) => {
  const newZoom = data.pageZoom + val;
  if (newZoom >= 0.5 && newZoom <= 3) {
    data.pageZoom = parseFloat(newZoom.toFixed(1));
    pageZoom.value = formatZoom(data.pageZoom);
    designRef.value.setZoom(pageZoom.value);
  }
};
const formatZoom = (value) => {
  // 展示的时候扩大100倍，并加上'%'
  return `${(value * 100).toFixed(0)}%`;
};
//清空
const handleClear = () => {
  designRef.value.setClear();
};
const previewDialog = ref(false);
const previewRef = ref();
const handlePreview = async () => {
  previewDialog.value = true;
  let hiprintTemplate = await designRef.value.getHiprintTemplate();
  //   let templateData = hiprintTemplate.getJson();
  previewRef.value.open(
    hiprintTemplate,
    printData,
    +data.paperValue.width + 10,
    +data.paperValue.height + 10,
    false
  );
};

const handleClodopPreview = async () => {
  let hiprintTemplate = await designRef.value.getHiprintTemplate();
  //getHtml可以传入数据
  let templateData = hiprintTemplate.getHtml(printData)[0].innerHTML;
  LodopPrint(templateData);
};
const handlePrint = async () => {
  let hiprintTemplate = await designRef.value.getHiprintTemplate();
  hiprintTemplate.print(
    printData,
    {
      callback: () => {
        loading.value = false;
      },
    },
    {
      styleHandler: () => {
        let css =
          '<link href="http://hiprint.io/Content/hiprint/css/print-lock.css" media="print" rel="stylesheet">';
        return css;
      },
    }
  );
};

const handleClodopPrint = () => {};
</script>
<style lang="scss" scoped></style>
